<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :modal-style="{ maxWidth: '520px' }"
    width="90%"
    @before-ok="save"
    @close="reset"
  >
    <GiForm ref="formRef" v-model="form" :options="options" :columns="columns">
      <template v-if="form.isShow" #password>
        <a-input-password v-model.trim="form.password" placeholder="请输入密码" :max-length="32" />
      </template>
    </GiForm>
</a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { addAccount, getAccount, updateAccount } from '@/apis/merchant/account'
import { type Columns, GiForm, type Options } from '@/components/GiForm'
import { encryptByRsa } from '@/utils/encrypt'
import { useForm } from '@/hooks'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const dataId = ref('')
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改商户列表' : '新增商户列表'))
const formRef = ref<InstanceType<typeof GiForm>>()

const options: Options = {
  form: {},
  col: { xs: 24, sm: 24, md: 24, lg: 24, xl: 24, xxl: 24 },
  btns: { hide: true }
}

const newColumns: Columns = [
  {
    label: '账户名',
    field: 'accountName',
    type: 'input'
  },
  {
    label: '密码',
    field: 'password',
    type: 'input-password'
  },
  {
    label: '推荐人邀请码',
    field: 'invitationCode',
    type: 'input'
  },
  {
    label: '是否商户',
    field: 'isShop',
    type: 'switch'
  }
]
const updateColumns: Columns = [
  {
    label: '账户名',
    field: 'accountName',
    type: 'input'
  },
  {
    label: '是否会员',
    field: 'isActive',
    type: 'switch'
  },
  {
    label: '是否商户',
    field: 'isShop',
    type: 'switch'
  }
]
const columns = computed(() => (isUpdate.value ? updateColumns : newColumns))

const { form, resetForm } = useForm({
  // todo 待补充
})

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

const visible = ref(false)
// 新增
const onAdd = () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  const res = await getAccount(id)
  Object.assign(form, res.data)
  visible.value = true
}

// 保存
const save = async () => {
  const rawPassword = form.password
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      await updateAccount(form, dataId.value)
      Message.success('修改成功')
    } else {
      if (rawPassword) {
        form.password = encryptByRsa(rawPassword) || ''
      }
      await addAccount(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

defineExpose({ onAdd, onUpdate })
</script>
